package com.blue.basic.data.test.pratice;

import java.math.BigDecimal;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author liulei, lei.liu@htouhui.com
 * @version 1.0
 */
public class Volitale {
    private static AtomicInteger casRace = new AtomicInteger(0);
    private static int syncRace = 0;
    private static volatile int volatileRace = 0;

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(10);
        int num = 1;
        long start = System.nanoTime();
        while (num <= 10) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 10000000; i++) {
                        syncIncrease();
                    }
                    latch.countDown();
                }
            }).start();
            num++;
        }
        latch.await();
        long end = System.nanoTime();
        System.out.println(new BigDecimal(end - start).divide(new BigDecimal(1000000000)));
        System.out.println(syncRace);
    }
    public static void volataleIncrease(){
        //数值不是预期的100000000，因为volatile只能保证可见性
        //++的操作，反编译会发现底层有4步操作，并不是原子弹，所以无法保证这种非原子操作场景的线程安全
        volatileRace++;
    }
    public static synchronized void syncIncrease() {
        //正确
        syncRace++;
    }
    public static void casIncrease() {
        //正确【CAS无锁，直接去内存中getAndSet值，底层调用compareAndSwap方法做while尝试修改循环，直至成功】
        casRace.getAndAdd(1);
    }
}
